package buildcode.support.plugin;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.ArrayUtils;

import buildcode.build.IPlugin;
import buildcode.config.EntityExportConfig;
import buildcode.database.DataBaseTable;
import buildcode.language.Type;
import buildcode.language.java.field.JavaDatabaseQueryField;
import buildcode.language.java.field.JavaField;
import buildcode.language.java.type.JavaEntity;
import buildcode.language.java.type.JavaXmlMapper;

public class TimeQueryFieldPlugin implements IPlugin {

    private String queryTimeStartFieldSuffix = "Start";

    private String queryTimeEndFieldSuffix = "End";

    private String[] requestTimeField;

    @Override
    public Type beforeExport(Type type, String contextId, List<DataBaseTable> bases, EntityExportConfig entityConfig) {
        if (requestTimeField.length == 0) {
            return type;
        }
        if (type instanceof JavaXmlMapper entity) {
            List<JavaDatabaseQueryField> queryFields = entity.getFields();
            List<JavaDatabaseQueryField> finallyFields = new ArrayList<JavaDatabaseQueryField>();
            for (JavaDatabaseQueryField field : queryFields) {
                if (ArrayUtils.contains(requestTimeField, field.getFieldName())) {
                    finallyFields.add(new JavaDatabaseQueryField(">=", field.getFieldName() + queryTimeStartFieldSuffix, "", field.getMetaData()));
                    finallyFields.add(new JavaDatabaseQueryField("&lt;=", field.getFieldName() + queryTimeEndFieldSuffix, "", field.getMetaData()));
                } else {
                    finallyFields.add(field);
                }
            }
            entity.setFields(finallyFields);
        } else if (type instanceof JavaEntity javaEntity) {
            List<JavaField> finallyFields = new ArrayList<JavaField>();
            for (JavaField field : javaEntity.getFields()) {
                if (ArrayUtils.contains(requestTimeField, field.getFieldName())) {
                    finallyFields.add(new JavaField(field.getFieldName() + queryTimeStartFieldSuffix, String.class, field.getRemark() + "-开始", field.getMetaData()));
                    finallyFields.add(new JavaField(field.getFieldName() + queryTimeEndFieldSuffix, String.class, field.getRemark() + "-结束", field.getMetaData()));
                } else {
                    finallyFields.add(field);
                }
            }
            javaEntity.setFields(finallyFields);
        }
        return type;
    }

    public TimeQueryFieldPlugin(String[] requestTimeField) {
        super();
        this.requestTimeField = requestTimeField;
    }

}
